package service

import (
	"dao"
	"pojo/form"
	"pojo/vo"
	"pojo/model"
	"constant"
		)

type GoodsService struct {
	dao *dao.GoodsDao
}

// 构造商品服务层
func NewGoodsService(dao *dao.GoodsDao) *GoodsService {
	return &GoodsService{
		dao: dao,
	}
}

// 保存商品信息
func (service *GoodsService) InsertGoods(goodsForm *form.GoodsForm) error {

	//cids := strings.Split(goodsForm.Cid, ",")
	//cid, _ := strconv.ParseUint(cids[len(cids)-1], 10, 64)

	goods := &model.Goods{
		Name:          goodsForm.Name,
		Price:         goodsForm.Price,
		DiscountPrice: goodsForm.DiscountPrice,
		Describe:      goodsForm.Describe,
		Cid:           goodsForm.Cid[len(goodsForm.Cid)-1],
	}

	_, err := service.dao.InsertGoods(goods)

	// todo 保存图片

	return err

}

// 修改商品信息
func (service *GoodsService) UpdateGoods(goodsForm *form.GoodsForm) error {

	//cids := strings.Split(goodsForm.Cid, ",")
	//cid, _ := strconv.ParseUint(cids[len(cids)-1], 10, 64)

	goods := &model.Goods{
		Name:          goodsForm.Name,
		Price:         goodsForm.Price,
		DiscountPrice: goodsForm.DiscountPrice,
		Describe:      goodsForm.Describe,
		Cid:           goodsForm.Cid[len(goodsForm.Cid)-1],
	}

	goods.ID = uint(goodsForm.Id)

	_, err := service.dao.UpdateGoods(goods)

	// todo 保存图片

	return err
}

// 分页查询商品信息
func (service *GoodsService) QueryGoods(queryForm *form.GoodsPageQueryForm) *vo.TableVo {

	result := &vo.TableVo{}
	result.Code = constant.SUCCESS.Code
	result.Msg = constant.SUCCESS.Msg

	size, _ := service.dao.Count(queryForm)
	result.Total = size

	if size > 0 {
		goods, _ := service.dao.List(queryForm)
		result.Items = goods
	}

	return result
}

// 根据id删除商品信息
func (service *GoodsService) DeleteGoods(id uint64) error {

	_, err := service.dao.DeleteGoods(id)

	return err
}

// 根据id查询商品信息
func (service *GoodsService) FindGoods(id uint64) (*model.Goods, error) {

	return service.dao.FindGoods(id)
}
